//
//  ViewController.swift
//  coinCalculator
//
//  Created by Qi-zhu on 2018/2/5.
//  Copyright © 2018年 Qi-zhu. All rights reserved.
//

import Cocoa
import WebKit

class ViewController: NSViewController {
    
    
    @IBOutlet weak var postLocalPrice: NSTextField!
    
    @IBOutlet weak var postOppositePrice: NSTextField!
    
    @IBOutlet weak var redeemOppositePrice: NSTextField!
    
    @IBOutlet weak var redeemLocalPrice: NSTextField!
    
    //汇率
    @IBOutlet weak var postRate: NSTextField!
    @IBOutlet weak var redeemRate: NSTextField!
    //结果
    @IBOutlet weak var result: NSTextField!
    //币种名
    @IBOutlet weak var postCoin: NSTextField!
    @IBOutlet weak var redeemCoin: NSTextField!
    //记事板
   
    @IBOutlet var memoPad: NSTextView!
    
    @IBOutlet weak var exchangeName: NSTextField!
    @IBOutlet weak var exchangeName_2: NSTextField!
    
    //MARK:webView
    var wkwebView:WKWebView?
    
    @IBOutlet weak var fetchButton_1: NSButton!
    @IBOutlet weak var fetchButton_2: NSButton!
    @IBOutlet weak var compareButton: NSButton!
    
    //参与比较结果交易对的过滤
    @IBOutlet weak var CNY_1: NSButton!
    @IBOutlet weak var USDT_1: NSButton!
    @IBOutlet weak var ETH_1: NSButton!
    @IBOutlet weak var BTC_1: NSButton!
    @IBOutlet weak var CNY_2: NSButton!
    @IBOutlet weak var USDT_2: NSButton!
    @IBOutlet weak var ETH_2: NSButton!
    @IBOutlet weak var BTC_2: NSButton!
    //有些网站需要从原网站抓取数据,数据量大时候网络操作频繁,可能会被锁ip或其他原因,所以可以选择是否进行处理,默认处理
    @IBOutlet weak var Process_1: NSButton!
    @IBOutlet weak var Process_2: NSButton!
    
    @IBOutlet weak var customRate: NSTextField!//允许自由设定汇率,在compare比较时会把值赋给self.dRate
    var dRate: Float = 6.25//当前美元汇率默认6.25,不同网址可能会不同
    var deltaRate: Float = 0.15 //deltaRate 上下浮动区间
    //MARK:web数据
    var fetchTag:Int = 0//当前正在处理Button(tag)的标记
    var dataDic_A:[String: Array<Array<String>>] = [:]//["红烧肉-Hshare":[["HSR/CNY","44.65"],["HSR/USDT"," 7.12"]]]
    var dataDic_B:[String: Array<Array<String>>] = [:]
//    var compareResArr:[]
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    @IBAction func calcuAction(_ sender: Any) {
        let postLocalNum = (self.postLocalPrice.stringValue as NSString).floatValue
        let postOppositeNum = (self.postOppositePrice.stringValue as NSString).floatValue
        let redeemOppositeNum = (self.redeemOppositePrice.stringValue as NSString).floatValue
        let redeemLocalNum = (self.redeemLocalPrice.stringValue as NSString).floatValue
        
        //post汇率模拟
        let postRateNum = postLocalNum/postOppositeNum
        postRate.stringValue = "\(postRateNum)"
        postRate.textColor = postRateNum > 6.5 ? NSColor.red : NSColor.black
        
        //redeem汇率模拟
        let redeemRateNum = redeemLocalNum/redeemOppositeNum
        redeemRate.stringValue = "\(redeemRateNum)"
        redeemRate.textColor = redeemRateNum > 6.5 ? NSColor.red : NSColor.black
        
        //总利率
        let total = postOppositeNum * redeemLocalNum / (postLocalNum * redeemOppositeNum)
        self.result.stringValue = "\(total)"
    }
    
    //交换
    @IBAction func switchCoinPosition(_ sender: Any) {
       
        var temp = postLocalPrice.stringValue
        postLocalPrice.stringValue = redeemLocalPrice.stringValue
        redeemLocalPrice.stringValue = temp
        
        temp = postOppositePrice.stringValue
        postOppositePrice.stringValue = redeemOppositePrice.stringValue
        redeemOppositePrice.stringValue = temp
        
        temp = postCoin.stringValue
        postCoin.stringValue = redeemCoin.stringValue
        redeemCoin.stringValue = temp
        
        calcuAction(sender)
    }
    
    //记录
    @IBAction func saveAction(_ sender: NSButton) {
        
        switch sender.tag {
        case 0:
            let string = "【\(postCoin.stringValue)】: \((postLocalPrice.stringValue as NSString).floatValue/(postOppositePrice.stringValue as NSString).floatValue) = \((postLocalPrice.stringValue as NSString).floatValue)/\((postOppositePrice.stringValue as NSString).floatValue)\n"
            memoPad.string = memoPad.string + string
        case 1:
            let string = "【\(redeemCoin.stringValue)】:\((redeemLocalPrice.stringValue as NSString).floatValue/(redeemOppositePrice.stringValue as NSString).floatValue) = \((redeemLocalPrice.stringValue as NSString).floatValue)/\((redeemOppositePrice.stringValue as NSString).floatValue)\n"
            memoPad.string = memoPad.string + string
        default:
            break
        }
    
    }
    
    @IBAction func fetchAction(_ sender: NSButton) {
        var exchageString = ""
        switch sender.tag {
        case 0:
            self.fetchTag = 0
            exchageString = self.exchangeName.stringValue
        case 1:
            self.fetchTag = 1
            exchageString = self.exchangeName_2.stringValue
        default:
            break
        }
        
        
        var urlString = "https://www.baidu.com"
        urlString = "https://www.feixiaohao.com/exchange/\(exchageString)/"
        print(urlString)
        let url = URL(string: urlString)
        let request = URLRequest(url: url!)
        
        if self.wkwebView == nil {
            let config = WKWebViewConfiguration()
            let webView = WKWebView(frame: .zero, configuration: config)
            webView.navigationDelegate = self
            self.wkwebView = webView
            self.view.addSubview(webView)
        }
        
        if exchageString != ""{
            fetchButton_1.isEnabled = false
            fetchButton_2.isEnabled = false
            sender.title = "process"
            
            self.wkwebView?.load(request)
        }else {
            sender.title = "Input"
        }
    }
    //MARK:比较
    @IBAction func compareAction(_ sender: NSButton){
        self.dRate = (self.customRate.stringValue as NSString).floatValue
        var rateArr:[Float] = []//记录所有rate的大小，用于排序
        var compareStringArr:[[String]] = []
        
        memoPad.string = ""
        if self.dataDic_A.count==0 || self.dataDic_B.count==0 {
            print("dataDic_A or dataDic_B no data")
            compareButton.title = "NoData"
            return
        } else {
            compareButton.title = "compare"
        }
        
        print("\(self.exchangeName.stringValue) \\ \(self.exchangeName_2.stringValue)")
        let exchageCompareName = "\(self.exchangeName.stringValue):\(dataDic_A.count)对 \\ \(self.exchangeName_2.stringValue):\(dataDic_B.count)对" + "\nProcessing\n\n"
        memoPad.string = memoPad.string + exchageCompareName

        for coin in self.dataDic_A {
            
            //偶尔会有空键值对夹杂在字典中跳过就行,总的数据并没有少
            if coin.key == "" {
                continue//
            }
            //参与比较的交易对的过滤的一些数组准备
            let filterStrArr = [CNY_1.title,USDT_1.title,ETH_1.title,BTC_1.title]
            let filterArr_1 = [CNY_1.state,USDT_1.state,ETH_1.state,BTC_1.state]
            let filterArr_2 = [CNY_2.state,USDT_2.state,ETH_2.state,BTC_2.state]
            
            let dataArr2 = self.dataDic_B[coin.key]
            for innerArr1 in coin.value {//遍历dicA中一个key下的所有交易对
                
                var continueFlag1 = false//是否需要跳过此交易对
                for (i,state) in filterArr_1.enumerated() {//过滤1中不需要的交易对
                    if state == .off {
                        if innerArr1[0].components(separatedBy: "/\(filterStrArr[i])").count > 1 {
                            continueFlag1=true
                            break
                        }
                    }
                }
                if continueFlag1 {continue}
                
                if let arr2 = dataArr2 {
                    for innerArr2 in arr2 {//遍历dicB中一个key下的所有交易对
                        
                        var continueFlag2 = false//是否需要跳过此交易对
                        for (i,state) in filterArr_2.enumerated() {//过滤1中不需要的交易对
                            if state == .off {
                                if innerArr2[0].components(separatedBy: "/\(filterStrArr[i])").count > 1 {
                                    continueFlag2=true
                                    break
                                }
                            }
                        }
                        if continueFlag2 {continue}
                        
                        let exchangePair1 = innerArr1[0]
                        let price1 = innerArr1[1]
                        let exchangePair2 = innerArr2[0]
                        let price2 = innerArr2[1]
                        
                        let priceNum1 = (price1 as NSString).floatValue
                        let priceNum2 = (price2 as NSString).floatValue
                        
                        let rate = priceNum1/priceNum2
                        //print("\(coin.key):==>\(rate) = (\(priceNum1) \\ \(priceNum2))\n")
                        
                        //第一段string ("ChatCoin":==>CHAT/CNY : CHAT/BTC)
                        let resultString1 = "\(coin.key)==>\(exchangePair1) : \(exchangePair2)\n"
                        //第二段string (1.02766 = (0.535 \ 0.5206))
                        let resultString2 = "\(rate) = (\(priceNum1) \\ \(priceNum2))\n\n"
                        
                        //按rate大小顺序插值到rateArr中,rateArr与compareStringArr同步
                        let strPair = [resultString1,resultString2]
                        if rateArr.count == 0 {//数组中只有0个和1个时情况比较特殊
                            rateArr.append(rate)
                            compareStringArr.append(strPair)
                        } else if rateArr.count == 1 {//数组中只有0个和1个时情况比较特殊
                            if rate<=rateArr[0] {
                                rateArr.insert(rate, at: 0)
                                compareStringArr.insert(strPair, at: 0)
                                
                            }else {
                                rateArr.append(rate)
                                compareStringArr.append(strPair)
                            }
                        } else {
                            for (i,r) in rateArr.enumerated() {
                                if i<=rateArr.count-2 {
                                    if rate >= rateArr[i]  && rate <= rateArr[i+1]{
                                        rateArr.insert(rate, at: i+1)
                                        compareStringArr.insert(strPair, at: i+1)
                                        break
                                    }
                                }else {
                                    if rate<=rateArr[0] {
                                        rateArr.insert(rate, at: 0)
                                        compareStringArr.insert(strPair, at: 0)
                                        break
                                    } else {
                                        rateArr.append(rate)
                                        compareStringArr.append(strPair)
                                        break
                                    }
                                }
                            }
                        }//排序完毕
                        
                    }//遍历dic2完毕
            }
            
        }//遍历dic1完毕
    }
        var attributColorRange:[NSRange] = []
        var rangeColor:[NSColor] = []
        for (i,rate) in rateArr.enumerated() {//开始生成富文本
            print(rate)
            let resultString1 = compareStringArr[i][0]//rate所对应的文字1 Dogecoin":==>DOGE/CNYT : DOGE/USDTsell
            let resultString2 = compareStringArr[i][1]//rate所对应的文字2 4.84 = (0.0242 \ 0.005)
            if resultString1.hasPrefix("\"OmiseGo") {
                
            }
            memoPad.string = memoPad.string + resultString1
//            print(memoPad.string)
            var sellIndex = 0
            var buyIndex = 0
            var symbolIndex = 0 //"/"分割号的位置,用于区分是buy和sell是这边的还是对面的
            //                if resultString1.components(separatedBy: "sell").count > 1 && resultString1.components(separatedBy: "buy").count > 1 {
            let rangeSell = resultString1.range(of: "sell")
            let rangeBuy = resultString1.range(of: "buy")
            let rangeSymbol = resultString1.range(of: ":")
            
            sellIndex = rangeSell?.lowerBound.encodedOffset ?? 0
            buyIndex = rangeBuy?.lowerBound.encodedOffset ?? 0
            symbolIndex = rangeSymbol?.lowerBound.encodedOffset ?? 0
        

            if resultString1.components(separatedBy: "buy").count > 2 || resultString1.components(separatedBy: "sell").count > 2 {//排除两个买的价格 或两个卖的价格互相比较
                memoPad.string = memoPad.string.replacingOccurrences(of: resultString1, with: "")
                continue
            }
            
            if (rate > 1.02 || rate < 0.98) && rate < 3{//高亮显示1/2 同货币(如ab站均为人民币购买)记录需要高亮的区域index
                let rateString = "\(rate)"
                
                if buyIndex != 0 && sellIndex != 0 && ((sellIndex<buyIndex && rate<0.98) || (buyIndex<sellIndex && rate>1.02)){//一卖一买,最好的情况,两边都有买一卖一价格
                    rangeColor.append(rate>1.02 ? NSColor.blue : NSColor.red)
                    attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                } else {//只有一方有买一或卖一的信息 或两边都没有买一卖一信息
                    
                    if rate>1.02 && ((sellIndex>symbolIndex && buyIndex==0)||(buyIndex<symbolIndex && sellIndex==0)){//数值越大需要对面是卖出才行,或者这边是买入
                        rangeColor.append(NSColor.blue )
                        attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                    } else if rate<0.98 && ((buyIndex>symbolIndex && sellIndex==0)||(sellIndex<symbolIndex && buyIndex==0)) {//数值越小则需要对面是买入,或这边是卖出
                        rangeColor.append(NSColor.red)
                        attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                    } else if buyIndex==0 && sellIndex==0{//不带sell或buy,都是直接从非小号获取的数据
                        rangeColor.append(rate>1.02 ? NSColor.blue : NSColor.red)
                        attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                    } else {//不属于任何情况,直接结束
                        memoPad.string = memoPad.string.replacingOccurrences(of: resultString1, with: "")
                        continue
                    }
                }
                
            }
            
            if rate > 3 && rate < 10{//高亮显示2/2 可能不是人民币比较,而是美元,当前网站美元汇率self.dRate来衡量
                if rate > self.dRate+self.deltaRate || rate < self.dRate-self.deltaRate {
                    let rateString = "\(rate)"
//                    if resultString1.hasPrefix("\"Status") {
//
//                    }
                    if buyIndex != 0 && sellIndex != 0 && ((sellIndex<buyIndex && rate<self.dRate-self.deltaRate) || (buyIndex<sellIndex && rate>self.dRate+self.deltaRate)){//一卖一买,最好的情况,两边都有买一卖一价格
                        rangeColor.append(rate>self.dRate+self.deltaRate ? NSColor.blue : NSColor.red)
                        attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                    }else {
                        
                        if rate>self.dRate+self.deltaRate && ((sellIndex>symbolIndex && buyIndex==0)||(buyIndex<symbolIndex && sellIndex==0)) {//数值越大需要对面是卖出才行,或者这边是买入
                            rangeColor.append(NSColor.blue )
                            attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                        } else if rate<self.dRate-self.deltaRate && ((buyIndex>symbolIndex && sellIndex==0)||(sellIndex<symbolIndex && buyIndex==0)) {
                            rangeColor.append(NSColor.red)//数值越小则需要对面是买入,或这边是卖出
                            attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                        } else if buyIndex==0 && sellIndex==0 {//不带sell或buy,都是直接从非小号获取的数据
                            rangeColor.append(rate>self.dRate+self.deltaRate ? NSColor.blue : NSColor.red)
                            attributColorRange.append(NSMakeRange(memoPad.string.count, rateString.count))
                        }else {//不属于任何情况,直接结束
                            memoPad.string  = memoPad.string.replacingOccurrences(of: resultString1, with: "")
                            continue
                        }
                    }
                    
                }
            }
            
            memoPad.string = memoPad.string + resultString2
        }
        
        print("Done")
        memoPad.string = memoPad.string + "Done\n***********\n现支持精确查询的交易所:\n1.coinw\n2.gate-io\n3.exx\n4.bjex\n5.bithumb\n6.aex\n***********\n"
        
        
        //根据attributColorRange为富文本添加颜色
        let attributedString = NSMutableAttributedString(string: memoPad.string)
        for (i,range) in attributColorRange.enumerated() {
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: rangeColor[i], range: range)
            
        }
//        let attr2 = NSMutableAttributedString(string: "我加上")
//        attr2.addAttribute(NSAttributedStringKey.foregroundColor, value: NSColor.green , range: NSMakeRange(0, 2))
//        attributedString.append(attr2)
        memoPad.textStorage?.setAttributedString(attributedString)
        
    }
}
//MARK: WKWEBVIEW
extension ViewController:WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("fetch_start")
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("fetch_finish")
        webView.evaluateJavaScript("document.documentElement.innerHTML") { (object, error) in
            if object != nil {
                let htmlString = object as! String
//                print(htmlString)
                self.process(htmlString: htmlString, tag: self.fetchTag)
//                self.fetchButton_1.isEnabled = true
//                self.fetchButton_2.isEnabled = true
//                (self.fetchTag == 0 ? self.fetchButton_1 : self.fetchButton_2)?.title = "Dnoe"
            } else {
                self.fetchButton_1.isEnabled = true
                self.fetchButton_2.isEnabled = true
                (self.fetchTag == 0 ? self.fetchButton_1 : self.fetchButton_2)?.title = "Error"
                print(error!)
            }
        
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("fail")
    }
    
}

//MARK:Process Data 处理
extension ViewController {
    
    func process(htmlString: String,tag:Int){
        print("process")
        let printSwitch = true //控制是否打印的开关
        var tempDic:[String:Array<Array<String>>] = [:]
        if htmlString.components(separatedBy: "Page Not Found").count > 1 {
            self.fetchButton_1.isEnabled = true
            self.fetchButton_2.isEnabled = true
            (self.fetchTag == 0 ? self.fetchButton_1 : self.fetchButton_2)?.title = "Error"
            print("Page Not Found 404")
            return
        }
        
        var tempArr = htmlString.components(separatedBy: "<tbody>")
        tempArr = tempArr[1].components(separatedBy: "</tbody>")
        let tbodyString = tempArr[0]//得到tbody
//        print(tbodyString)
        
        let trArr = tbodyString.components(separatedBy: "</tr>")//得到存有很多tr的数组
//        print(trArr[0])
        for tr in trArr {
            let tdArr = tr.components(separatedBy: "</td>")//得到存有很多td的数组
            
            var infoArr:[String] = []
            var coinName:String = ""
            
            for (i,td) in tdArr.enumerated() {
                let celltd = td.components(separatedBy: ">")//截取每个td内的<td>之后</td>之前的数据
                
                if celltd.count > 1 {
//                    print("=============\(celltd[1])")

                    if i == 1 {//
                        let tempArr = celltd[2].components(separatedBy: "alt=")
                        if tempArr.count > 1 {
                           if printSwitch==true{print("币名\(tempArr[1])")}//coinName
                            coinName = tempArr[1]
                        }
                    }
                    
                    if i == 2 {
                        var exchangePair = celltd[1]
                        if celltd[1].components(separatedBy: "href").count > 1 {//有些交易对带有可以点击的链接,需要在这里处理,需要的数据在celltd[2]中
                            exchangePair = celltd[2].components(separatedBy: "<")[0]
                            
                        }
                        exchangePair = exchangePair.replacingOccurrences(of: " ", with: "")
                        if printSwitch==true{print("交易对\(exchangePair)")}
                        infoArr.append(exchangePair)
                    }
                    
                    if i == 3 {//下标为3时包含价格信息
                        var priceString:String = ""
                        
                        var tempArr = celltd[1].components(separatedBy: "¥")//去除"¥"
                        if tempArr.count > 1 {//
                            tempArr = tempArr[1].components(separatedBy: ",")//去除","
                            for temp in tempArr {
                                priceString = priceString + temp
                            }
                        } else {
                            print("//未获取到有效数据")
                            priceString = "-1"
                        }
                        let price = (priceString as NSString).floatValue//价格
                        if printSwitch==true{print("价格\(price)")}
                        infoArr.append(priceString)
                    }
                }
            }
            if tempDic[coinName] != nil{//对于同一币种，不同交易对，全都对应同一个key，用数组保存
//                var arr = tempDic[coinName]
               tempDic[coinName]!.append(infoArr)
            } else {
                var arr = [infoArr]
                tempDic.updateValue(arr, forKey: coinName)
            }
//                tempDic.updateValue(infoArr, forKey: coinName)
        }
      
        var exString = ""
        var status = self.fetchTag==0 ? Process_1.state : Process_2.state
        if tag == 0 {
            self.dataDic_A = tempDic
            exString = self.exchangeName.stringValue
        } else {
            self.dataDic_B = tempDic
            exString = self.exchangeName_2.stringValue
        }
        
        if exString == "coinw" && status == .on{
            processCoinwData {
//                self.setBtnStatus()
                //特殊处理,已经在processCoinwData内部调用过了
            }
        }
        else if exString == "gate-io" {
            processGateioData {
                self.setBtnStatus()
            }
        }else if exString == "bjex" && status == .on{
            
            processBJEXData {
                self.setBtnStatus()
            }
        }else if exString == "exx"{
            processExxData {
                self.setBtnStatus()
            }
        }else if exString == "bithumb"{
            processBithumbData {
                self.setBtnStatus()
            }
        }else if exString == "aex"{
            processAexData {
                
            }
        }else{//非gate-io的数据
            setBtnStatus()
        }
        
    }//func
    
    func setBtnStatus(statusString: String = "Fetch",isActive: Bool = true,setComareText: Bool = true){
        self.fetchButton_1.isEnabled = isActive
        self.fetchButton_2.isEnabled = isActive
        
        (self.fetchTag == 0 ? self.fetchButton_1 : self.fetchButton_2)?.title = statusString
        print("finish_process")
        if setComareText == true {
            self.compareAction(NSButton())
        }
    }
    
    func processGateioData(finishBlock: @escaping ()->Void){//用gate-io的买一卖一替换非小号的价格数据
//        self.dRate = 6.5
        let request = QZHttpBaseManager(url: "http://data.gateio.io/api2/1/tickers")
        request.getMethodJsonData({ (json) in
            var gateDic = json.dictionaryValue
            for gateRow in gateDic {//将所有key变为和webDic中格式一致stx_cny ==>  STX/CNY
                let key = gateRow.key
                let newKey = key.replacingOccurrences(of: "_", with: "/")
                gateDic.updateValue(gateRow.value, forKey: newKey.uppercased())
            }
            
            let dataDic = self.fetchTag==0 ? self.dataDic_A : self.dataDic_B
            for webRow in dataDic{//遍历非小号所有币种
                var webValue = webRow.value
                if webRow.key == "" {//跳过空数据
                    continue
                }
                
                var removeIndex = 0//要移除的下标(从第0个开始移除,若没有移除则向后下次从下一位开始)
                for (i,pair) in webValue.enumerated() {//遍历一个币种包含的所有的交易对
                    let pairString = pair[0]
                    if let value = gateDic[pairString]?.dictionary {//在gate-io字典中查找
                        let sellPrice = value["lowestAsk"]?.floatValue
                        let buyPrice = value["highestBid"]?.floatValue
                        webValue.append(["\(pairString)sell","\(sellPrice ?? -1)"])//在非小号得到的数组中加上从gate-io得到的数据
                        webValue.append(["\(pairString)buy","\(buyPrice ?? -1)"])
                        webValue.remove(at: removeIndex)//移除非小号的数据
//                        print(webValue)
                        
                    }else {//在gate-io中没有对应的交易对,webValue没有执行移除原有交易对,
                        removeIndex += 1
                    }
                }
                if self.fetchTag==0 {
                    self.dataDic_A.updateValue(webValue, forKey: webRow.key)
                }else {
                    self.dataDic_B.updateValue(webValue, forKey: webRow.key)
                }
            }
            finishBlock()
            
        }) { (error) in
            print(error)
            self.setBtnStatus(statusString: "gatenetErr")
        }
    }
    
    func processExxData(finishBlock: @escaping ()->Void){//用exx的买一卖一替换非小号的价格数据
        
        let request = QZHttpBaseManager(url: "https://api.exx.com/data/v1/tickers")
        request.getMethodJsonData({ (json) in
            var exxDic = json.dictionaryValue
            for gateRow in exxDic {//将所有key变为和webDic中格式一致stx_cny ==>  STX/CNY
                let key = gateRow.key
                let newKey = key.replacingOccurrences(of: "_", with: "/")
                exxDic.updateValue(gateRow.value, forKey: newKey.uppercased())
            }
            
            let dataDic = self.fetchTag==0 ? self.dataDic_A : self.dataDic_B
            for webRow in dataDic{//遍历非小号所有币种
                var webValue = webRow.value
                if webRow.key == "" {//跳过空数据
                    continue
                }
                var removeIndex = 0//要移除的下标(从第0个开始移除,若没有移除则向后下次从下一位开始)
                for (i,pair) in webValue.enumerated() {//遍历一个币种包含的所有的交易对
                    let pairString = pair[0]//LTC/USDT
                    
                    if let value = exxDic[pairString]?.dictionary {//在exx字典中查找
                        let sellPrice = value["sell"]?.floatValue
                        let buyPrice = value["buy"]?.floatValue
                        webValue.append(["\(pairString)sell","\(sellPrice ?? -1)"])//在非小号得到的数组中加上从exx得到的数据
                        webValue.append(["\(pairString)buy","\(buyPrice ?? -1)"])
                        print(webValue[i])
                        webValue.remove(at: removeIndex)//移除非小号的数据
                        
                        print(webValue)
//                        continue//找到了就继续下一个
                    }else {//在exx中没有对应的交易对,webValue没有执行移除原有交易对,
                        removeIndex += 1
                    }
                }
                if self.fetchTag==0 {
                    self.dataDic_A.updateValue(webValue, forKey: webRow.key)
                }else {
                    self.dataDic_B.updateValue(webValue, forKey: webRow.key)
                }
            }
            finishBlock()
            
        }) { (error) in
            print(error)
            self.setBtnStatus(statusString: "exxnetErr")
        }
    }
    
    //Bjex不能先进行查找,因为他本身在非小号不能取到数据,但是compareAction依靠非小号的中文币种名进行筛选比较,所以他需要借助另一个网站在非小号的数据制作dataDic筛选
    //出现结果重复现象可能是因为与之比较的交易对包含买一卖一,这样就会出现重复了
    func processBJEXData(finishBlock: @escaping ()->Void){
//        self.dRate = 6.5
        let request = QZHttpBaseManager(url: "http://open.yobtc.cn/app/trademarket/v1/api/allticker")
        request.getMethodJsonData({ (json) in
            
            var tickersArr = json["tickers"].arrayValue
            let dataDic = self.fetchTag==1 ? self.dataDic_A : self.dataDic_B//取另一个输入框的dataDic
            
            var tickersDic:[String: PairModel] = [:]
            for ticketRow in tickersArr{//将所有key变为和webDic中格式一致stx_cny ==>  STX/CNY
                let key = ticketRow["transactionpair"].stringValue
                let newKey = key.replacingOccurrences(of: "_", with: "/")
                
                let model = PairModel()
                model.pairName = newKey.uppercased()
                model.sellPrice = ticketRow["sellprice"].stringValue
                model.buyPrice = ticketRow["buyprice"].stringValue
                
                //用前半部分作为key,这样才可以在之后用它来查找,原有的key仍旧保存在model.pairName中
                let finalKey = model.pairName.components(separatedBy: "/")[0]
                
                tickersDic.updateValue(model, forKey: finalKey)
            }
            
//            var newDataDic = dataDic
            for webRow in dataDic{//遍历非小号所有币种
                var webValue = webRow.value
                if webRow.key == "" {//跳过空数据
                    continue
                }
//                var newWebValue = webRow.value
                var removeIndex = 0
                for (i,pair) in webValue.enumerated() {//遍历一个币种包含的所有的交易对
                    var pairString = pair[0]// HSR/CNYT
                    if pairString.hasPrefix("WIC")  {
                        pairString = "WICC"
                    }
                    if pairString.hasPrefix("BCC")  {
                        pairString = "BCH"
                    }
                    let comArr = pairString.components(separatedBy: "/")
                    let prePair = comArr[0] //HSR 截取前半部分来作为key进行查找
                    if let model = tickersDic[prePair] {//在bjex字典中查找
                        let sellPrice = (model.sellPrice as NSString).floatValue
                        let buyPrice = (model.buyPrice as NSString).floatValue
                        webValue.append(["\(model.pairName)sell","\(sellPrice ?? -1)"])//在非小号得到的数组中加上从bjex得到的数据
                        webValue.append(["\(model.pairName)buy","\(buyPrice ?? -1)"])

//                        print(webValue)
//                      continue//找到了就继续下一个
                    }
                    webValue.remove(at: removeIndex)//无论能不能找到都要移除非小号的数据
                    
                }
                if self.fetchTag==0 {
                    self.dataDic_A.updateValue(webValue, forKey: webRow.key)
                }else {
                    self.dataDic_B.updateValue(webValue, forKey: webRow.key)
                }
            }
            finishBlock()
     
        }) { (error) in
            print(error)
            self.setBtnStatus(statusString: "bjexnetErr")
        }
    }
    
    func processCoinwData(finishBlock: @escaping ()->Void){
//        https://www.coinw.me/appApi.html?action=market&symbol=20
        
            var dataDic = self.fetchTag==0 ? self.dataDic_A : self.dataDic_B
            
            let otherDataDic = self.fetchTag==1 ? self.dataDic_A : self.dataDic_B//取另一个输入框的dataDic
            
            let group1 = DispatchGroup()
            var totalTask = 0
            var finishTask = 0
            var errTask = 0
            for coin in getSymbolDic() {
            let coinName = coin.key
            let symbol = coin.value
                
                print("一个任务进入")
                totalTask += 1
                group1.enter()
                let request = QZHttpBaseManager(url: "https://www.coinw.me/appApi.html?action=market&symbol=\(symbol)")
                request.getMethodJsonData({ (json) in
                    let buyPrice = json["buy"].float ?? -1.0
                    let sellPrice = json["sell"].float ?? -1.0
                    
                    var originPairStr = dataDic[coinName]?[0][0] ?? ""//["红烧肉-Hshare":[["HSR/CNY","44.65"],["HSR/USDT"," 7.12"]]]
                   
                    if originPairStr == "" {
                        originPairStr = self.getCoinPairPrefixByCoinName(coinName: coinName) + "/CNYT"
                    }
                    
                    let newArr = [["\(originPairStr)buy","\(buyPrice)"],["\(originPairStr)sell","\(sellPrice)"]]
//                    dataDic.updateValue(newArr, forKey: coinName)
                    
                    if self.fetchTag==0 {
                        self.dataDic_A.updateValue(newArr, forKey: coinName)
                    }else {
                        self.dataDic_B.updateValue(newArr, forKey: coinName)
                    }
                    print("一个任务完成")
                    print("\(coinName)\(newArr)")
                    finishTask += 1
                    group1.leave()
                    self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: false,setComareText: false)
                    //1.调度组,2.dataDic的生命周期
                }){ (error) in
                    print(error)
                    print("一个任务失败")
                    errTask += 1
                    group1.leave()
                    self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: false,setComareText: false)
                }
            
        }
            
            group1.notify(queue: DispatchQueue.main, execute: {
                self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: true)
            })
        
    
    }
    
    func processBithumbData(finishBlock: @escaping ()->Void){
    
        let request = QZHttpBaseManager(url: "https://api.bithumb.com/public/ticker/all")
        request.getMethodJsonData({ (json) in
            let jsonDic = json["data"].dictionaryValue
            let dataDic = self.fetchTag==0 ? self.dataDic_A : self.dataDic_B
            
            var bithumbDic: [String: PairModel] = [:]
            for coin in jsonDic {
                if coin.key == "date" {
                    continue
                }
                
              let model = PairModel()
              model.pairName = coin.key.uppercased() + "/KRW"
              model.buyPrice = coin.value["buy_price"].string ?? ""
              model.sellPrice = coin.value["buy_price"].string ?? ""
                
                bithumbDic.updateValue(model, forKey: model.pairName)
            }
            
            for webRow in dataDic{//遍历非小号所有币种
                var webValue = webRow.value
                if webRow.key == "" {//跳过空数据
                    continue
                }
                //                var newWebValue = webRow.value
                for (i,pair) in webValue.enumerated() {//遍历一个币种包含的所有的交易对
                    let pairString = pair[0]// HSR/CNYT
//                    let comArr = pairString.components(separatedBy: "/")
//                    let prePair = comArr[0] //HSR 截取前半部分来作为key进行查找
                    if let model = bithumbDic[pairString] {//在bjex字典中查找
                        let sellPrice = (model.sellPrice as NSString).floatValue
                        let buyPrice = (model.buyPrice as NSString).floatValue
                        webValue.append(["\(model.pairName)sell","\(sellPrice ?? -1)"])//在非小号得到的数组中加上从bjex得到的数据
                        webValue.append(["\(model.pairName)buy","\(buyPrice ?? -1)"])
                        
                        //                        print(webValue)
                        //                      continue//找到了就继续下一个
                    }
                    webValue.remove(at: 0)//移除非小号的数据
                }
                if self.fetchTag==0 {
                    self.dataDic_A.updateValue(webValue, forKey: webRow.key)
                }else {
                    self.dataDic_B.updateValue(webValue, forKey: webRow.key)
                }
            }
            
            finishBlock()
            
        }) { (error) in
            self.setBtnStatus(statusString: "BitErr")
        }
    
    }
    
    func processAexData(finishBlock: @escaping ()->Void){

        
        let typeArr = ["cnc","usdt","bitcny","btc"]
//        let typeArr = ["bitcny"]
        let group1 = DispatchGroup()
        var totalTask = 0
        var finishTask = 0
        var errTask = 0
        
        var  aexDic: [String: PairModel] = [:]
        for type in typeArr {
    
            print("一个任务进入")
            totalTask += 1
            group1.enter()
            
            let request = QZHttpBaseManager(url: "https://api.aex.com/ticker.php?c=all&mk_type=\(type)")
            request.getMethodJsonData({ (json) in
                
                
                var checkFlag = 0
                for coin in json.dictionaryValue {
                    checkFlag += 1
                    let model = PairModel()
                    model.pairName = (coin.key + "/\(type)").uppercased()
                    model.buyPrice = "\(coin.value["ticker"]["buy"].float ?? -1)"
                    model.sellPrice = "\(coin.value["ticker"]["sell"].float ?? -1)"
                    
                    aexDic.updateValue(model, forKey: model.pairName)
                }
                
                if checkFlag == 0 {
                    print("一个任务失败")
                    errTask += 1
                } else {
                    print("一个任务完成")
                    finishTask += 1
                }
               
                group1.leave()
                self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: false,setComareText: false)
            }) { (error) in
                print(error)
                print("一个任务失败")
                errTask += 1
                group1.leave()
                self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: false,setComareText: false)
            }
        }
        
        group1.notify(queue: DispatchQueue.main, execute: {
            print("aexDic\(aexDic)")
            
            var dataDic = self.fetchTag==0 ? self.dataDic_A : self.dataDic_B
            for webRow in dataDic{//遍历非小号所有币种
                var webValue = webRow.value
                if webRow.key == "" {//跳过空数据
                    continue
                }
                
                var removeIndex = 0//
                for (i,pair) in webValue.enumerated() {//遍历一个币种包含的所有的交易对
                    let pairString = pair[0]// HSR/CNYT
                    if pairString.hasSuffix("BITCNY") {
                        
                    }
                    if let model = aexDic[pairString] {//在aex字典中查找
                        let sellPrice = (model.sellPrice as NSString).floatValue
                        let buyPrice = (model.buyPrice as NSString).floatValue
                        webValue.append(["\(model.pairName)sell","\(sellPrice ?? -1)"])//在非小号得到的数组中加上从aex得到的数据
                        webValue.append(["\(model.pairName)buy","\(buyPrice ?? -1)"])
                        
                        //                        print(webValue)
                        //                      continue//找到了就继续下一个
                        webValue.remove(at: removeIndex)//移除非小号的数据
                    }else {
                        removeIndex += 1
                    }
                }
                if self.fetchTag==0 {
                    self.dataDic_A.updateValue(webValue, forKey: webRow.key)
                }else {
                    self.dataDic_B.updateValue(webValue, forKey: webRow.key)
                }
            }
            self.setBtnStatus(statusString: "\(finishTask)/\(errTask)/\(totalTask)",isActive: true)
        })
    }
}

//MARK: 杂项
extension ViewController {//处理时会用的一些杂项
    func getSymbolDic()-> [String: Int] {//为coinw设置的
        
        let dic = ["\"BabyCoin-币宝\"":2,"\"Litecoin-莱特币\"":3,"\"Hshare-红烧肉\"":5,
                   "\"Stox-拳王币\"":6,"\"0x-0x协议\"":7,"\"Blox\"":8,
                   "\"Tierion\"":9,"\"Decentraland\"":10,"\"OmiseGo-嫩模币\"":11,
                   "\"Kyber Network\"":12,"\"Ethereum-以太坊\"":14,"\"Aeternity-阿姨币\"":15,
                   "\"Streamr\"":16,"\"Hyperpay\"":17,"\"Datum\"":18,
                   "\"Oneroot\"":19,"\"DEW\"":20,"\"Maggie Token-麦奇\"":21,
                   "\"Storj\"":23,"\"Status\"":24,"\"Dogecoin-狗狗币\"":25,
                   "\"WaykiChain-维基链\"":28,"\"EOS-柚子\"":29,"\"SDChain-六域链\"":30,
                   "\"Coins\"":31,"\"BitDegree\"":32,"\"ChatCoin\"":33,
                   "\"IHTCoin-云产币\"":34,"\"Gladius Token\"":35,"\"RealChain-真链\"":36,
                   "\"Portal\"":37,"\"Enjin Coin-恩金币\"":38,"\"Energy Eco Chain-易能链\"":39,
                   "\"OceanChain-海洋币\"":40,"\"Electronic PK Chain-电竞链\"":41,"\"MTC Mesh network\"":42,//mtc不知为何物
                   "\"eosDAC\"":44,"\"Bitcoin-比特币\"":45,"\"System Working Token China-斯微特\"":47,
                   "\"EKT-通用积分\"":48,"\"BCD-比特币钻石\"":53]
        
//        var dic = ["\"币宝-BabyCoin\"":2,"\"莱特币-Litecoin\"":3,"\"红烧肉-Hshare\"":5,
//                   "\"拳王币-Stox\"":6,"\"0x协议-0x\"":7,"\"Blox\"":8,
//                   "\"Tierion\"":9,"\"Decentraland\"":10,"\"嫩模币-OmiseGo\"":11,
//                   "\"Kyber Network\"":12,"\"以太坊-Ethereum\"":14,"\"阿姨币-Aeternity\"":15,
//                   "\"Streamr\"":16,"\"Hyperpay\"":17,"\"Datum\"":18,
//                   "\"Oneroot\"":19,"\"DEW\"":20,"\"麦奇-Maggie Token\"":21,
//                   "\"Storj\"":23,"\"Status\"":24,"\"狗狗币-Dogecoin\"":25,
//                   "\"维基链-WaykiChain\"":28,"\"柚子-EOS\"":29,"\"六域链-SDChain\"":30,
//                   "\"Coins\"":31,"\"BitDegree\"":32,"\"ChatCoin\"":33,
//                   "\"云产币-IHTCoin\"":33,"\"Gladius Token\"":35,"\"真链-RealChain\"":36,
//                   "\"Portal\"":37,"\"恩金币-Enjin Coin\"":38,"\"易能链-Energy Eco Chain\"":39,
//                   "\"海洋币-OceanChain\"":40,"\"电竞链-Electronic PK Chain\"":41,"\"MTC Mesh network\"":42,//mtc不知为何物
//            "\"eosDAC\"":44,"\"比特币-Bitcoin\"":45,"\"斯微特-System Working Token China\"":47,
//            "\"通用积分-EKT\"":48,"\"比特币钻石-BCD\"":53]
        
        return dic
    }
    
    func getCoinPairPrefixByCoinName(coinName: String)->String {
        
        var dic = ["\"BabyCoin-币宝\"":"BC","\"Litecoin-莱特币\"":"LTC","\"Hshare-红烧肉\"":"HSR",
                   "\"Stox-拳王币\"":"STX","\"0x-0x协议\"": "0X","\"Blox\"":"CDT",
                   "\"Tierion\"":"TNT","\"Decentraland\"":"MANA","\"OmiseGo-嫩模币\"":"OMG",
                   "\"Kyber Network\"":"KNC","\"Ethereum-以太坊\"":"ETH","\"Aeternity-阿姨币\"":"AE",
                   "\"Streamr\"":"DATA","\"Hyperpay\"":"HPY","\"Datum\"":"DAT",
                   "\"Oneroot\"":"RNT","\"DEW\"":"DEW","\"Maggie Token-麦奇\"":"MAG",
                   "\"Storj\"":"STORJ","\"Status\"":"SNT","\"Dogecoin-狗狗币\"":"DOGE",
                   "\"WaykiChain-维基链\"":"WICC","\"EOS-柚子\"":"EOS","\"SDChain-六域链\"":"SDA",
                   "\"Coins\"":"Coins","\"BitDegree\"":"BDG","\"ChatCoin\"":"CHAT",
                   "\"IHTCoin-云产币\"":"IHT","\"Gladius Token\"":"GLA","\"RealChain-真链\"":"RCT",
                   "\"Portal\"":"PORTAL","\"Enjin Coin-恩金币\"":"ENJ","\"Energy Eco Chain-易能链\"":"EET",
                   "\"OceanChain-海洋币\"":"OC","\"Electronic PK Chain-电竞链\"":"EPC","\"MTC Mesh network\"":"MTC",//mtc不知为何物
            "\"eosDAC\"":"EOSDAC","\"Bitcoin-比特币\"":"BTC","\"System Working Token China-斯微特\"":"SWTC",
            "\"EKT-通用积分\"":"EKT","\"BCD-比特币钻石\"":"BCD"]
        
        return dic[coinName] ?? "未知"
    }
}

class PairModel: NSObject {
    var pairName: String = "默认pairName"//交易对名称
    var sellPrice: String = "默认sell"//卖一价
    var buyPrice: String = "默认buy"//买一价
}
